<template>
  <el-dialog :title="title" :visible.sync="showDialog" @close="closeDialog" :close-on-click-modal="false" append-to-body>
    <BaseForm :fields="fields" :form-data.sync="innerFormData" v-bind="$attrs" ref="baseForm" @submit="submit" :primary-id="primaryId">
      <template #[field.slot]="{value}" v-for="field in slots">
        <slot :name="field.slot" :value="value"></slot>
      </template>
      <template #footer-button>
        <div class="text-right w-full">
          <el-button size="medium"  @click.native="closeDialog">取消</el-button>
          <el-button size="medium" type="primary" @click.native="confirmForm">确认</el-button>
        </div>
      </template>
    </BaseForm>
  </el-dialog>
</template>

<script>
export default {
  name: "DialogForm",
  props:{
    value: {
      type: Boolean ,
      default: false
    } ,
    primaryId: null ,
    title: '' ,
    fields:{
      type: Array ,
      required: true
    },
    formData: {
      type: Object ,
      required: true
    }
  },
  data(){
    return {
      innerFormData:{}
    }
  },
  computed:{
    slots(){
      return this.fields.filter(f=>{
        return !f.slot
      })
    },
    showDialog:{
      get(){
        return this.value ;
      },
      set(value){
        this.$emit("input",value)
        this.$emit("update:value",value)
        if(!value){
          this.resetFields()
        }

      }
    }
  },
  watch:{
    value(val){
      if(val){
        this.innerFormData = Object.assign({} ,this.formData )
      }
    }
  },
  methods:{
    resetFields(){
      this.$refs.baseForm.resetFields()
    },
    closeDialog(){
      this.showDialog = false ;
    },
    confirmForm(){
      this.$refs.baseForm.submit()
    },
    submit(data){
      this.$emit("submit",data)
      this.closeDialog() ;
    }

  }
}
</script>

<style scoped>

</style>